package com.yunyouyi.grabtickets.service.impl;

import com.yunyouyi.grabtickets.mapper.TicketMapper;
import com.yunyouyi.grabtickets.redis.RedisService;
import com.yunyouyi.grabtickets.service.TicketService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class TicketServiceImpl implements TicketService {

    @Resource
    private RedisService redisService;

    @Resource
    private TicketMapper ticketMapper;

    @Async  // 异步写 DB，确保主线程快返回
    public void updateDbStock(String trainId) {
        ticketMapper.updateStock(trainId);  // DB中 stock - 1，无需 version 乐观锁
    }

    @Override
    public boolean buy(String trainId) {
        Long stock = redisService.decrStock("stock:" + trainId);
        if (stock == null || stock < 0) {
            return false;  // 库存不足或key不存在
        }

        // 异步写数据库，保证最终一致性
        updateDbStock(trainId);
        return true;
    }
}